<template>
  <div class="approvals-container">
    <el-card class="approvals-card">
      <template #header>
        <div class="card-header">
          <h3>审批管理</h3>
          <div class="header-actions">
            <el-select v-model="filterStatus" placeholder="状态筛选" clearable>
              <el-option label="待处理" :value="0" />
              <el-option label="已通过" :value="1" />
              <el-option label="已拒绝" :value="2" />
            </el-select>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="approvalsList"
        style="width: 100%"
      >
        <el-table-column prop="applyUserName" label="申请人" width="120" />
        <el-table-column label="申请类型" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.activityId ? 'success' : 'warning'">
              {{ scope.row.activityId ? '活动申请' : '社团申请' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="applyedName" label="申请对象" width="150" />
        <el-table-column prop="applyContent" label="申请内容" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ scope.row.applyContent || '无申请内容' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="申请时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === 0"
              type="success"
              size="small"
              @click="handleApprove(scope.row)"
            >
              通过
            </el-button>
            <el-button
              v-if="scope.row.status === 0"
              type="danger"
              size="small"
              @click="handleReject(scope.row)"
            >
              拒绝
            </el-button>
            <el-button
              type="primary"
              size="small"
              @click="showDetail(scope.row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      title="申请详情"
      width="600px"
    >
      <div v-if="currentDetail" class="detail-content">
        <div class="detail-item">
          <span class="label">申请人：</span>
          <span>{{ currentDetail.applyUserName }}</span>
        </div>
        <div class="detail-item">
          <span class="label">申请类型：</span>
          <span>{{ currentDetail.activityId ? '活动申请' : '社团申请' }}</span>
        </div>
        <div class="detail-item">
          <span class="label">申请对象：</span>
          <span>{{ currentDetail.applyedName }}</span>
        </div>
        <div class="detail-item">
          <span class="label">申请内容：</span>
          <span>{{ currentDetail.applyContent || '无申请内容' }}</span>
        </div>
        <div class="detail-item">
          <span class="label">申请时间：</span>
          <span>{{ formatDateTime(currentDetail.createdAt) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">状态：</span>
          <el-tag :type="getStatusType(currentDetail.status)">
            {{ getStatusText(currentDetail.status) }}
          </el-tag>
        </div>
        <div class="detail-item">
          <span class="label">更新时间：</span>
          <span>{{ formatDateTime(currentDetail.updatedAt) }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from '@/utils/axios'
import dayjs from 'dayjs'

const loading = ref(false)
const approvalsList = ref([])
const filterStatus = ref('')
const total = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)
const detailVisible = ref(false)
const currentDetail = ref(null)

// 获取审批列表
const getApprovalsList = async () => {
  loading.value = true
  try {
    const response = await axios.get('/registration/loadDataList', {
      params: {
        pageNo: currentPage.value,
        pageSize: pageSize.value,
        status: filterStatus.value
      }
    })
    if (response.status === 'success' && response.code === 200) {
      approvalsList.value = response.data.list || []
      total.value = response.data.totalCount || 0
      pageSize.value = response.data.pageSize || 10
      currentPage.value = response.data.pageNo || 1
    } else {
      ElMessage.warning(response.info || '获取数据失败')
    }
  } catch (error) {
    console.error('获取审批列表失败:', error)
    ElMessage.error('获取审批列表失败')
  } finally {
    loading.value = false
  }
}

// 处理状态筛选变化
watch(filterStatus, () => {
  currentPage.value = 1
  getApprovalsList()
})

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  getApprovalsList()
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '待处理',
    1: '已通过',
    2: '已拒绝'
  }
  return statusMap[status] || '未知状态'
}

// 获取状态标签类型
const getStatusType = (status) => {
  const typeMap = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return typeMap[status] || 'info'
}

// 处理通过申请
const handleApprove = async (row) => {
  try {
    await ElMessageBox.confirm('确定通过该申请吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await axios.post('/registration/updateRegistrationById', {
      id: row.id,
      status: 1
    })
    
    if (response.status === 'success' && response.code === 200) {
      ElMessage.success('审批通过成功')
      getApprovalsList()
    } else {
      ElMessage.error(response.info || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('审批失败:', error)
      ElMessage.error('审批失败')
    }
  }
}

// 处理拒绝申请
const handleReject = async (row) => {
  try {
    await ElMessageBox.confirm('确定拒绝该申请吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await axios.post('/registration/updateRegistrationById', {
      id: row.id,
      status: 2
    })
    
    if (response.status === 'success' && response.code === 200) {
      ElMessage.success('已拒绝该申请')
      getApprovalsList()
    } else {
      ElMessage.error(response.info || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

// 显示详情
const showDetail = (row) => {
  currentDetail.value = row
  detailVisible.value = true
}

// 格式化时间
const formatDateTime = (time) => {
  return time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '--'
}

onMounted(() => {
  getApprovalsList()
})
</script>

<style scoped>
.approvals-container {
  padding: 20px;
}

.approvals-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 15px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.detail-content {
  padding: 20px;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.detail-item .label {
  width: 100px;
  color: #606266;
  font-weight: bold;
}
</style> 